package coap.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import coap.Configuration;

public class UDPNetwork {

	private DatagramSocket socket = null;
	private ReceiverThread receiverThread = null;
	MessageHandler handler = null;

	public UDPNetwork(int port, MessageHandler handler) {
		this.handler = handler;
		try {
			if (port != -1)
				socket = new DatagramSocket(port);
			else
				socket = new DatagramSocket();
		} catch (Exception e) {
			e.printStackTrace();
		}
		receiverThread = new ReceiverThread();
	}

	public void start() {
		receiverThread.start();
	}

	public void stop() {
		receiverThread.terminate();
	}

	public void send(byte[] data, int offset, int len, InetAddress address, int port) {


        DatagramPacket packet = new DatagramPacket(data, offset, len, address,
				port);
        try {
		    socket.send(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }

	private class ReceiverThread extends Thread {

		private boolean running = true;

		public void terminate() {
			running = false;
		}

		@Override
		public void run() {
			try {
				byte[] buf = new byte[Configuration.MAX_PACKET_SIZE];
				while (running) {
					DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);
					handler.handleMessage(buf, packet.getLength(), packet
							.getAddress(), packet.getPort());
				}
				System.out.println("Receiver thread terminated");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
